<template>
    <div class="search-page">
        <a-space direction="vertical">
            <a-input-search v-model:value="value" placeholder="请输入文章标题" enter-button :loading="isLoading" allowClear
                @search="onSearch" />
        </a-space>
        <a-table class="table" :columns="columns" :dataSource="postsList" :pagination="false">
            <template #bodyCell="{ column, record }">
                <a-space v-if="column.dataIndex === 'image'">
                    <img style="width:60px;heigth:60px" :src="record.image" :alt="record.title">
                </a-space>
                <a-space v-if="column.dataIndex === 'author'">
                    {{ record.student ? record.student.stuName : record.admin.account }}
                </a-space>
                <a-space v-if="column.dataIndex === 'createdAt'">
                    {{ dayjs(record.createdAt).format('YYYY-MM-DD') }}
                </a-space>
                <a-space v-if="column.dataIndex === 'operate'">
                    <a-button @click="detailRow(record.id)">详情</a-button>
                </a-space>
            </template>
        </a-table>
    </div>
</template>

<script setup lang='ts'>
import dayjs from 'dayjs'
import { message } from 'ant-design-vue';
import type { Post } from '@/types/posts';
const value = ref<string>('')

const onSearch = async (searchValue: string) => {
    isLoading.value = true
    searchValue ? await getList(searchValue) : postsList.value = []
    isLoading.value = false
}

const isLoading = ref(false)

const columns = [
    { title: '标题', dataIndex: 'title' },
    { title: '封面', dataIndex: 'image' },
    { title: '作者', dataIndex: 'author' },
    { title: '发布时间', dataIndex: 'createdAt' },
    { title: '操作', dataIndex: 'operate' }
]

const postsList = ref<Post[]>([])

const getList = async (title: string) => {
    const res = await searchByTitle(title)
    if (res.code !== 201) return message.warning('找不到该文章')
    postsList.value = res.data.post
}

const router = useRouter()
const detailRow = async (id: number) => {
    // console.log(id)
    router.push({
        path: `/detail/${id}`,
        query: {
            posts: id
        }
    })
}

</script>

<style scoped lang="less">
.table {
    margin-top: 20px;
}
</style>